package com.bwie.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUploadUtils {
	
	
	public static String upload(MultipartFile photo) {
		String realPath ="";
		try {
			if(!photo.isEmpty()) {
				//Ҫ�ϴ���·��
				//String realPath = session.getServletContext().getRealPath("D:\\workspace\\upload\\");
				 realPath = "D:/upload/";

				//��ȡ�ļ���ԭʼ����
				String originalFilename = photo.getOriginalFilename();

				if(originalFilename.endsWith(".png")||originalFilename.endsWith(".jpg")||originalFilename.endsWith(".jpeg")||originalFilename.endsWith(".mp4")) {
					//String replace = UUID.randomUUID().toString().replace("-", "");

					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
					String replace = dateFormat.format(new Date());

					String filename = replace+originalFilename;
					File file = new File(realPath,filename);
					photo.transferTo(file);
					realPath += filename;
				}
			}
		} catch (Exception e) {
			//�ڿ���̨��ӡ�쳣
			e.printStackTrace();
		}
		return realPath;
	}

	//读取图片
	public static void showImg(String path, HttpServletResponse response){
		if(path!=null&&!path.equals("")){

		try {
			FileInputStream fis = new FileInputStream(path);
			ServletOutputStream os = response.getOutputStream();

			byte [] b = new byte[1024*8];
			while(fis.read(b)!=-1){
				os.write(b);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		}
	}

}
